package com.yanqu.road.server.manager.assistant;

import com.yanqu.road.entity.assistant.enums.eAssistantEscortCartState;
import com.yanqu.road.entity.beautyescort.EscortBeautyDispatch;
import com.yanqu.road.entity.beautyescort.EscortCartData;
import com.yanqu.road.entity.beautyescort.EscortCartDataHelper;
import com.yanqu.road.entity.beautyescort.enums.eEscortCartState;
import com.yanqu.road.entity.enums.eItemId;
import com.yanqu.road.entity.player.UserBaseInfo;
import com.yanqu.road.pb.assistant.AssistantProto;
import com.yanqu.road.pb.beautyescort.BeautyEscortProto;
import com.yanqu.road.server.TempMgr;
import com.yanqu.road.server.manager.beautyescort.CrossBeautyEscortMgr;
import com.yanqu.road.server.manager.beautyescort.CrossEscortPlayerWrap;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.utils.property.Property;
import com.yanqu.road.utils.property.PropertyHelper;
import com.yanqu.road.utils.string.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.util.*;
import java.util.stream.Collectors;

public class CrossAssistantMgr extends TempMgr {

    public static final Logger logger = LogManager.getLogger(CrossAssistantMgr.class.getName());

    @Override
    public boolean init() throws Exception {
        return false;
    }

    @Override
    public boolean reloadConfig() throws Exception {
        return false;
    }

    @Override
    public boolean reloadData() throws Exception {
        return false;
    }

    @Override
    public boolean stop() {
        return false;
    }


    /**
     * 自动押镖
     */
    public static void autoDispatchDart(AssistantProto.AssistantActionRespMsg.Builder assistantActionRespMsg, long serverId, long userId, List<EscortBeautyDispatch> dispatchList, List<EscortBeautyDispatch> noDispatchList, UserBaseInfo userBaseInfo) {
        CrossEscortPlayerWrap playerWrap = CrossBeautyEscortMgr.getEscortPlayer(serverId, userId);
        AssistantProto.AssistantBeautyEscortCartRespMsg.Builder escortRespMsg = AssistantProto.AssistantBeautyEscortCartRespMsg.newBuilder();
        if (playerWrap == null) {
            playerWrap = CrossBeautyEscortMgr.initEscortPlayer(serverId, userId, userBaseInfo);
        }
        // 在押镖中的美女
        List<Integer> escortingBeautyIdList = playerWrap.getEscortingBeautyIdList();
        List<EscortBeautyDispatch> escortingBeautyDispatchList = dispatchList.stream().filter(beautyDispatch -> escortingBeautyIdList.contains(beautyDispatch.getBeautyId())).collect(Collectors.toList());

        Map<Integer, AssistantProto.AssistantBeautyEscortCartTemp.Builder> cartRespMsgMap = new HashMap<>();
        // 先处理领奖操作
        for (Map.Entry<Integer, EscortCartData> cartDataEntry : playerWrap.getCartDataMap().entrySet()) {
            AssistantProto.AssistantBeautyEscortCartTemp.Builder cartRespMsg = AssistantProto.AssistantBeautyEscortCartTemp.newBuilder();
            // 封装押镖信息
            EscortCartData cartData = cartDataEntry.getValue();
            synchronized (cartData) {
                if (cartData.getState() == eEscortCartState.Finish.getIntValue()) {
                    Property reward = StringUtils.isNullOrEmpty(escortRespMsg.getReward()) ? new Property() : PropertyHelper.parseStringToProperty(escortRespMsg.getReward());
                    // 自动处理镖车事件
                    cartData.setAutoHandleEvent(true);
                    playerWrap.autoHandleCartEvent(cartData);
                    // 领取奖励
                    BeautyEscortProto.BeautyEscortGetEventRewardRespMsg.Builder eventRewardRespMsg = playerWrap.getEventReward(cartData.getCartId(), cartData.getDartId());
                    if (eventRewardRespMsg.getRet() == 0) {
                        reward.addProperty(PropertyHelper.parseStringToProperty(eventRewardRespMsg.getReward()));
                        cartRespMsg.setEventReward(eventRewardRespMsg);
                    }
                    EscortCartDataHelper helper = playerWrap.getDartReward(cartData.getCartId(), cartData.getDartId());
                    if (helper.getRet() != 0) {
                        cartRespMsg.setRet(helper.getRet());
                        cartRespMsg.setCart(CrossBeautyEscortMgr.getCartSimpleBuilder(cartData));
                    } else {
                        reward.addProperty(helper.getReward());
                        EscortCartData idleCart = helper.getIdleCart();
                        cartRespMsg.setRet(0);
                        cartRespMsg.setCart(CrossBeautyEscortMgr.getCartSimpleBuilder(idleCart));
                        // 添加镖车奖励
                        BeautyEscortProto.BeautyEscortGetDartRewardRespMsg.Builder dartRewardMsg = BeautyEscortProto.BeautyEscortGetDartRewardRespMsg.newBuilder();
                        dartRewardMsg.setRet(0);
                        dartRewardMsg.setDartId(idleCart.getDartId());
                        dartRewardMsg.setReward(PropertyHelper.parsePropertyToString(helper.getReward()));
                        dartRewardMsg.setExp(helper.getReward().getCountByGoodsId(eItemId.BEAUTY_ESCORT_EXP_GOODS.getValue()).intValue());
                        dartRewardMsg.addAllBeauty(CrossBeautyEscortMgr.parseBeautyDispatchBuilderList(idleCart.getBeautyDispatchList()));
                        cartRespMsg.setDartReward(dartRewardMsg);
                        List<Integer> beautyIdList = new ArrayList<>();
                        for (EscortBeautyDispatch beautyDispatch : idleCart.getBeautyDispatchList()) {
                            beautyIdList.add(beautyDispatch.getBeautyId());
                        }
                        cartRespMsg.setDispatchIds(StringUtils.listToString(beautyIdList, ","));
                        cartRespMsg.setDispatchType(eAssistantEscortCartState.Finish.getIntValue());
                        // 有免费次数，可继续派遣，免费次数不足，则移除
                        beautyIdList.forEach(beautyId -> {
                            escortingBeautyDispatchList.removeIf(escortingBeauty -> escortingBeauty.getBeautyId() == beautyId);
                            // 领奖时当为默认派遣，所以要+1
                            if (dispatchList.stream().anyMatch(dispatch -> dispatch.getBeautyId() == beautyId)
                                    && getBeautyLeftDispatchTimes(dispatchList, beautyId) + 1 <= 0) {
                                // 不可继续派遣
                                dispatchList.stream().filter(escortBeautyDispatch -> escortBeautyDispatch.getBeautyId() == beautyId).findFirst().ifPresent(noDispatchList::add);
                                dispatchList.removeIf(dispatch -> dispatch.getBeautyId() == beautyId);
                            }
                        });
                    }
                    escortRespMsg.setReward(PropertyHelper.parsePropertyToString(reward));
                    cartRespMsgMap.put(cartData.getCartId(), cartRespMsg);
                }
            }
        }
        // 美女根据魅力值降序,剩余派遣次数降序
        dispatchList.sort((a, b) -> a.getGlamour() == b.getGlamour() ? Integer.compare(a.getLeftDispatchTime(), b.getLeftDispatchTime()) : a.getGlamour() > b.getGlamour() ? -1 : 1);
        // 押镖操作
        for (Map.Entry<Integer, EscortCartData> cartDataEntry : playerWrap.getCartDataMap().entrySet()) {
            // 封装押镖信息
            EscortCartData cartData = cartDataEntry.getValue();
            //synchronized (cartData) {
                AssistantProto.AssistantBeautyEscortCartTemp.Builder cartRespMsg = cartRespMsgMap.getOrDefault(cartData.getCartId(), AssistantProto.AssistantBeautyEscortCartTemp.newBuilder());
                // 空闲的镖车且剩余可派遣的美女>5时才处理
                if (cartData.getState() == eEscortCartState.Idle.getIntValue()) {
                    boolean isDispatch = false;
                    if (dispatchList.size() >= 5) {
                        // 需要派遣的列表
                        List<EscortBeautyDispatch> needDispatchList = new ArrayList<>();
                        // 派遣
                        while (dispatchList.size() > 0 && needDispatchList.size() < 5) {
                            EscortBeautyDispatch dispatch = dispatchList.get(0);
                            if (!escortingBeautyDispatchList.contains(dispatch)) {
                                needDispatchList.add(dispatch);
                            } else {
                                // 忙，没有派遣
                                noDispatchList.add(dispatch);
                            }
                            dispatchList.remove(dispatch);
                        }
                        if (needDispatchList.size() >= 5) {
                            // 随机生成委托人
                            playerWrap.randomClient();
                            // 普通类型镖车  type 0
                            EscortCartDataHelper helper = playerWrap.genEscortCartData(playerWrap.getUserData().getClientList().remove(0), 0, needDispatchList, false, 0);
                            if (helper.getRet() != 0) {
                                cartRespMsg.setRet(helper.getRet());
                                cartRespMsg.setCart(CrossBeautyEscortMgr.getCartSimpleBuilder(cartData));
                            } else {
                                // 派遣成功
                                EscortCartData idleCart = helper.getIdleCart();
                                cartRespMsg.setRet(0);
                                cartRespMsg.setCart(CrossBeautyEscortMgr.getCartSimpleBuilder(idleCart));
                                isDispatch = true;
                                // 添加助手派遣状态
                                if (cartRespMsg.getDispatchType() == eAssistantEscortCartState.Finish.getIntValue()) {
                                    cartRespMsg.setDispatchType(eAssistantEscortCartState.FinishAndDispatch.getIntValue());
                                } else {
                                    cartRespMsg.setDispatchType(eAssistantEscortCartState.Dispatch.getIntValue());
                                }
                                cartRespMsg.addAllDispatchBeauty(CrossBeautyEscortMgr.parseBeautyDispatchBuilderList(needDispatchList));
                            }
                        } else {
                            // 不满足派遣条件加回派遣列表
                            dispatchList.addAll(needDispatchList);
                        }
                    }
                    if (!isDispatch) {
                        // 美女人数不足，跳过处理
                        cartRespMsg.setRet(GameErrorCode.E_BEAUTY_ESCORT_DISPATCH_NUM_ERROR);
                        cartRespMsg.setCart(CrossBeautyEscortMgr.getCartSimpleBuilder(cartData));
                        // 添加助手派遣状态
                        if (cartRespMsg.getDispatchType() != eAssistantEscortCartState.Finish.getIntValue()) {
                            cartRespMsg.setDispatchType(eAssistantEscortCartState.NoDispatch.getIntValue());
                        }
                    }
                } else if (cartData.getState() == eEscortCartState.Escorting.getIntValue()) {
                    // 进行中的跳过处理
                    // 获取当前镖车的信息
                    cartRespMsg.setRet(0);
                    cartRespMsg.setDispatchType(eAssistantEscortCartState.Escorting.getIntValue());
                    cartRespMsg.setCart(CrossBeautyEscortMgr.getCartSimpleBuilder(cartData));
                }
                cartRespMsgMap.put(cartData.getCartId(), cartRespMsg);
            //}
        }
        // 剩下的均为未派遣的美女
        noDispatchList.addAll(dispatchList);
        escortRespMsg.setRet(0);
        // 镖车信息
        cartRespMsgMap.values().forEach(escortRespMsg::addCartList);
        assistantActionRespMsg.setAssistantBeautyEscortCartRespMsg(escortRespMsg);
    }

    private static int getBeautyLeftDispatchTimes(List<EscortBeautyDispatch> dispatchList, int beautyId) {
        return dispatchList.stream()
                .filter(dispatch -> dispatch.getBeautyId() == beautyId)
                .findFirst()
                .map(EscortBeautyDispatch::getLeftDispatchTime)
                .orElse(0);
    }


}
